package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"red-book-shop/cahce"
	"red-book-shop/models"
	"red-book-shop/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户名和密码不能为空",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户名不存在",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	contentBook := c.PostForm("contentBook")
	img := c.PostForm("img")
	if title == "" || content == "" || contentBook == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.RedBook{

		Title:       title,
		Content:     content,
		ContentBook: contentBook,
		Img:         img,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "发布失败",
		})
		return
	}
	Redis_key := "Redis_add_" + strconv.Itoa(int(data.ID))
	var user models.RedBook
	models.DB.Where("id=?", data.ID).First(&user)
	jsonData, _ := json.Marshal(user)
	cahce.Rdb.Set(cahce.Ctx, Redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var list models.RedBook
	err := models.DB.Where("id=?", id).First(&list).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "详情失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情成功",
		"list": list,
	})
}
func Del(c *gin.Context) {
	id := c.Query("id")
	var arr models.RedBook
	RedisKey := "redis_del_" + id
	models.DB.Where("id=?", id).Delete(&arr)
	cahce.Rdb.Del(cahce.Ctx, RedisKey)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
func List(c *gin.Context) {
	var arr []models.RedBook
	redis_key := "redis_key_"
	redisData, _ := cahce.Rdb.Get(cahce.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Find(&arr)
		jsonData, _ := json.Marshal(arr)
		cahce.Rdb.Set(cahce.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}
